package com.jia.together.controller.front;

import com.jia.together.entity.Member;
import com.jia.together.entity.vo.LoginVo;
import com.jia.together.entity.vo.MemberOthersVo;
import com.jia.together.entity.vo.PasswordVo;
import com.jia.together.service.MemberService;
import com.jia.together.utils.R;
import com.jia.together.utils.RandomUtil;
import com.jia.together.utils.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/front/member")
//@CrossOrigin
public class MemberFrontController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JavaMailSender javaMailSender;

    @PostMapping("/login/password")
    public R loginPassword(@RequestBody Member member){
        Map<String,Object> map = memberService.loginOrRegisterPassword(member);
        return R.ok().data(map);
    }
    @GetMapping("/sendEmailCode")
    public R sendEmailCode(@RequestParam String email){
        String sixCode = RandomUtil.getSixBitRandom();

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("佳家伴途");
        mailMessage.setText("校验码为："+ sixCode);
        mailMessage.setFrom("980436918@qq.com");
        mailMessage.setTo(email);
        javaMailSender.send(mailMessage);

        redisUtil.set("CODE_"+email,sixCode,60);
        return R.ok();
    }
    @PostMapping("/login/code")
    public R loginCode(@RequestBody LoginVo loginVo){
        Map<String,Object> map = memberService.loginOrRegisterCode(loginVo);
        return R.ok().data(map);
    }

    @PostMapping("/changePassword")
    public R changePassword(@RequestBody PasswordVo PasswordVo){
        memberService.changePassword(PasswordVo);
        return R.ok();
    }

    @PostMapping("/update")
    public R update(@RequestBody Member member){
        memberService.updateById(member);
        return R.ok();
    }

    @GetMapping("/getInfoByToken")
    public R getInfoByToken(HttpServletRequest request){
        Member member = memberService.selectInfoByToken(request);
        return R.ok().data("data",member);
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable String id){
        Member byId = memberService.getById(id);
        return R.ok().data("data",byId);
    }
    @GetMapping("/getMemberOthers/{id}")
    public R getMemberOthers(@PathVariable String id){
        MemberOthersVo memberOthersVo = memberService.selectMemberOthers(id);
        return R.ok().data("data",memberOthersVo);
    }
}
